package com.epalmpay.service.yunstream.impl;

import com.epalmpay.bean.OilCardDenominationBean;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.oilcard.OilcardInDTO;
import com.epalmpay.dto.oilcard.OilcardListOutDTO;
import com.epalmpay.dto.oilcard.OilcardMemberInDTO;
import com.epalmpay.dto.oilcard.OilcardMemberListOutDTO;
import com.epalmpay.dto.oilcard.OilcardMemberOutDTO;
import com.epalmpay.dto.oilcard.OilcardOutDTO;
import com.epalmpay.entity.Group;
import com.epalmpay.entity.Member;
import com.epalmpay.entity.Page;
import com.epalmpay.entity.YsOilcard;
import com.epalmpay.entity.YsOilcardMember;
import com.epalmpay.mapper.*;
import com.epalmpay.service.yunstream.IOilCardService;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Logger;
import com.epalmpay.util.Response;
import com.epalmpay.util.SysUtils;
import com.epalmpay.util.Tools;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;



@Service("oilCardService")
public class OilCardServiceImpl implements IOilCardService {

	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource
	private YsOilcardMemberMapper ysOilcardMemberMapper;
	@Resource
	private YsOilcardMapper ysOilcardMapper;
	@Resource
	private YsOilcardOrderMapper ysOilcardOrderMapper;
	@Resource
	private GroupMapper groupMapper;
	
	@Resource
	private  MemberMapper memberMapper;
	
	//油卡列表
	@Override
	public OilcardListOutDTO getOilcardList(OilcardInDTO oilcardInDTO, Page page) throws Exception {
		OilcardListOutDTO oilcardListOutDTO = new OilcardListOutDTO();
		Map<String,Object> param=new HashMap<String,Object>();
		
		param.put("oilcardType",oilcardInDTO.getOilcardType());
		param.put("discount",oilcardInDTO.getDiscount());
		param.put("groupId",oilcardInDTO.getGroupId());
		int sumCount = ysOilcardMapper.queryOilcardCount(param);
		
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return oilcardListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		
		List<OilcardOutDTO> oilcardOutDTOList = ysOilcardMapper.queryOilcardList(param);
		oilcardListOutDTO.setOilcardOutDTOList(oilcardOutDTOList);
		return oilcardListOutDTO;
	}

	
	@Override
	public YsOilcard findOilcardStatus(Long id) throws Exception {
		return ysOilcardMapper.selectByPrimaryKey(id);
	}


	//更新状态
	@Override
	public void updateStatus(YsOilcard ysOilcard) throws Exception {
		if (ysOilcard.getIsStartuse().intValue()==1) {
			ysOilcard.setIsStartuse(0);
		}
		else{
			ysOilcard.setIsStartuse(1);
		}
		ysOilcardMapper.updateByPrimaryKeySelective(ysOilcard);
	}

	@Override
	public OilcardOutDTO deleteOilcard(Long oilcardId) throws Exception {
		OilcardOutDTO oilcardOutDTO=new OilcardOutDTO();
        YsOilcard ysOilcard= ysOilcardMapper.selectByPrimaryKey(oilcardId);
        if(ysOilcard!=null){
        	ysOilcard.setIsStartuse(-99);
        	int result=ysOilcardMapper.updateByPrimaryKey(ysOilcard);
        	if(result<0){
   			  oilcardOutDTO.setErrorCode("9876","数据库操作失败");			 
   		  }else{
   			  oilcardOutDTO.setErrorCode(Rescode.SUCCESS,"删除油卡成功");
   		  }
        }else{
        	 oilcardOutDTO.setErrorCode("9876","数据不存在");		
        }
		return oilcardOutDTO;
	}

//	//新增油卡套餐
//	@Override
//	public OilcardOutDTO saveOilcard(OilcardInDTO oilcardInDTO) throws Exception {
//		YsOilcard oilcard = new YsOilcard();
//		oilcardInDTO.setLimitAmount(oilcardInDTO.getLimitAmount());
//		oilcard.setCountNum(oilcardInDTO.getCountNum());
//		PropertyCopyUtil.copyPropertiesExclude(oilcardInDTO,oilcard);
//		oilcard.setGmtCreate(new Date());
//		oilcard.setGmtModified(new Date());
//		ysOilcardMapper.insertSelective(oilcard);
//		return;
//	}

	@Override
	public OilcardOutDTO saveOilcard(OilcardInDTO oilcardInDTO) throws Exception{
		OilcardOutDTO oilcardOutDTO=new OilcardOutDTO();
		int result=0;
		//防止重复添加
		YsOilcard  t=ysOilcardMapper.findOilcardByTypeCount(oilcardInDTO.getOilcardType(),oilcardInDTO.getType(),oilcardInDTO.getCountNum(),oilcardInDTO.getGroupId());
		String alertMsg="创建油卡";
    	if(oilcardInDTO.getId()!=null&&oilcardInDTO.getId()>0){
    		alertMsg="编辑油卡";
    	}	
		if( t!=null&&!t.getId().equals(oilcardInDTO.getId())){
			logger.info(t.getId()+"....."+oilcardInDTO.getId());
			 oilcardOutDTO.setErrorCode("8743", "同一类型油卡同一套餐重复");
			 return oilcardOutDTO ;
		}
		//如果当前选择是默认选择 将其他设置为非默认选择
		if(oilcardInDTO.getIsDefault()){
			ysOilcardMapper.setNotDefaultOilCardByType(oilcardInDTO.getOilcardType(),oilcardInDTO.getGroupId());
		}
		if(oilcardInDTO.getId()!=null&&oilcardInDTO.getId()>0){
			YsOilcard oilcardtemp=ysOilcardMapper.selectByPrimaryKey(oilcardInDTO.getId());
			
			oilcardtemp.setType(oilcardInDTO.getType());
			oilcardtemp.setOilcardType(oilcardInDTO.getOilcardType());
			oilcardtemp.setCountNum(oilcardInDTO.getCountNum());
			oilcardtemp.setDiscount(oilcardInDTO.getDiscount());
			oilcardtemp.setLimitAmount(oilcardInDTO.getLimitAmount());
			oilcardtemp.setSort(oilcardInDTO.getSort());
			oilcardtemp.setIsStartuse(oilcardInDTO.getIsStartuse());
			oilcardtemp.setIsDefault(oilcardInDTO.getIsDefault());
			oilcardtemp.setSaleBase(oilcardInDTO.getSaleBase());
			oilcardtemp.setUpdater(oilcardInDTO.getUpdater());
			oilcardtemp.setGmtModified(new Date());
			oilcardtemp.setGroupId(oilcardInDTO.getGroupId());		
			result= ysOilcardMapper.updateByPrimaryKey(oilcardtemp);
		}else{
			
			YsOilcard oilcardtemp=new YsOilcard();
			oilcardtemp.setType(oilcardInDTO.getType());
			oilcardtemp.setOilcardType(oilcardInDTO.getOilcardType());
			oilcardtemp.setCountNum(oilcardInDTO.getCountNum());
			oilcardtemp.setDiscount(oilcardInDTO.getDiscount());
			oilcardtemp.setLimitAmount(oilcardInDTO.getLimitAmount());
			oilcardtemp.setSort(oilcardInDTO.getSort());
			oilcardtemp.setIsStartuse(oilcardInDTO.getIsStartuse());
			oilcardtemp.setIsDefault(oilcardInDTO.getIsDefault());
			oilcardtemp.setSaleBase(oilcardInDTO.getSaleBase());
			oilcardtemp.setSaleAmount(0);
			oilcardtemp.setUpdater(oilcardInDTO.getUpdater());
			oilcardtemp.setGmtModified(new Date());
			oilcardtemp.setCreater(oilcardInDTO.getUpdater());
			oilcardtemp.setGmtCreate(new Date());
			oilcardtemp.setGroupId(oilcardInDTO.getGroupId());	
			result= ysOilcardMapper.insert(oilcardtemp);
		}
		
		 if(result<0){
			 oilcardOutDTO.setErrorCode("9876",alertMsg+"数据库操作失败");
			 
		  }else{
			  oilcardOutDTO.setErrorCode(Rescode.SUCCESS,alertMsg+"成功");
		  }
		
		 return oilcardOutDTO ;
	}
	
	
	@Override
	public YsOilcard findOilcardById(YsOilcard oilcard) throws Exception {
		
		return ysOilcardMapper.findOilcardById(oilcard);
	}

//
//	@Override
//	public OilcardOutDTO editOilcard(OilcardInDTO oilcardInDTO) throws Exception {
//		YsOilcard oilcard = new YsOilcard();
//		oilcard.setId(oilcardInDTO.getId());
//		oilcard.setType(oilcardInDTO.getType());
//		oilcard.setOilcardType(oilcardInDTO.getOilcardType());
//		oilcard.setCountNum(oilcardInDTO.getCountNum());
//		oilcard.setDiscount(oilcardInDTO.getDiscount());
//		oilcard.setLimitAmount(oilcardInDTO.getLimitAmount());
//		oilcard.setSort(oilcardInDTO.getSort());
//		oilcard.setIsStartuse(oilcardInDTO.getIsStartuse());
//		oilcard.setIsDefault(oilcardInDTO.getIsDefault());
//		oilcard.setSaleBase(oilcardInDTO.getSaleBase());
//		oilcard.setUpdater(oilcardInDTO.getUpdater());
//		oilcard.setGmtModified(new Date());
//		ysOilcardMapper.updateByPrimaryKeySelective(oilcard);
//	}



	@Override
	public OilcardOutDTO queryData(OilcardInDTO oilcardInDTO) throws Exception {
		
		return ysOilcardMapper.queryData(oilcardInDTO);
	}




	
	
	//用户油卡列表
	@Override
	public OilcardMemberListOutDTO getOilcardMemberList(OilcardMemberInDTO oilcardMemberInDTO, Page page)
			throws Exception {
		OilcardMemberListOutDTO oilcardMemberListOutDTO = new OilcardMemberListOutDTO();
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId",oilcardMemberInDTO.getGroupId());
		param.put("oilcardType",oilcardMemberInDTO.getOilcardType());
		param.put("oilcardNumber",oilcardMemberInDTO.getOilcardNumber());
		param.put("memberName",oilcardMemberInDTO.getMemberName());
		param.put("memberPhone", oilcardMemberInDTO.getMemberPhone());
		int sumCount = ysOilcardMemberMapper.queryOilcardMemberCount(param);
		page.setTotalResult(sumCount);
		if(sumCount<=0)
			return oilcardMemberListOutDTO;
		
		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount()*(page.getCurrentPage()-1));
		List<OilcardMemberOutDTO> oilcardMemberOutDTOList = ysOilcardMemberMapper.queryOilcardMemberList(param);
		oilcardMemberListOutDTO.setOilcardMemberOutDTOList(oilcardMemberOutDTOList);
		return oilcardMemberListOutDTO;
	}

	

	public Map<String, Object> getOilCardList(String memberId) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();

		List<YsOilcardMember> ysOilcardMemberList = ysOilcardMemberMapper.selectByMemberId(Long.parseLong(memberId));
		if(ysOilcardMemberList!=null&&ysOilcardMemberList.size()>0){
			List<Map<String,Object>> oilCardList = new ArrayList<Map<String, Object>>();
			boolean hasDefault=false;
			for(YsOilcardMember ysOilcardMember:ysOilcardMemberList){
				Map<String, Object> detail = new HashMap<String, Object>();
				detail.put("id",ysOilcardMember.getId());
				detail.put("gmtCreate", DateUtil.fomatDate(ysOilcardMember.getGmtCreate(),DateUtil.sdfTime));
				detail.put("gmtModified", DateUtil.fomatDate(ysOilcardMember.getGmtModified(),DateUtil.sdfTime));
				detail.put("oilcardNumber", ysOilcardMember.getOilcardNumber());
				detail.put("oilcardOwen",ysOilcardMember.getOilcardName());
				detail.put("oilcardPhone", ysOilcardMember.getOilcardPhone());
				detail.put("oilcardType", ysOilcardMember.getOilcardType());
				if(ysOilcardMember.getIsDefault()){
					detail.put("isDefault", 1);
					hasDefault=true;
				}else{
					detail.put("isDefault", 0);
				}		
				oilCardList.add(detail);
			}
			
			if(oilCardList.size()>0) {
				if(!hasDefault){
					//将第一个设置为默认
					oilCardList.get(0).put("isDefault", 1);
				}
				map.put("oilCardList", oilCardList);
			}
		}
		
		return map;
	}


	@Override
	//增加油卡
	public int addOilCard(String memberId,String oilcardNumber,String oilcardOwen,String oilcardPhone,String oilcardType,Integer isDefault) throws Exception{
		int result = 0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL,"memberId 不能为空！");
		}
		if (Tools.isEmpty(oilcardNumber)) {
			throw new ApplicationException(Rescode.FAIL,"oilcardNumber 不能为空！");
		}
		if (Tools.isEmpty(oilcardOwen)) {
			throw new ApplicationException(Rescode.FAIL,"oilcardOwen 不能为空！");
		}
		if (Tools.isEmpty(oilcardPhone)) {
			throw new ApplicationException(Rescode.FAIL,"oilcardPhone 不能为空！");
		}
		if (Tools.isEmpty(oilcardType)) {
			throw new ApplicationException(Rescode.FAIL,"oilcardType 不能为空！");
		}
		if(isDefault == null || (isDefault != 0 && isDefault != 1)) {
			throw new ApplicationException(Rescode.FAIL, "isDefault 值不对！");
		}

		int count = 0;
		count = ysOilcardMemberMapper.selectCardNumberCount(Long.parseLong(memberId),oilcardNumber,null);
		if(count >0)
			throw new ApplicationException(Rescode.FAIL, "油卡号重复！");

		if(isDefault ==1) {
			//count = ysOilcardMemberMapper.selectDefaultCount(Long.parseLong(memberId));
			//if (count > 0)
			//	throw new ApplicationException(Rescode.FAIL, "默认油卡已经有了！");
			//更新其它金额
            count = ysOilcardMemberMapper.updateRecordToUnDefault(Long.parseLong(memberId));
		}


		YsOilcardMember record = new YsOilcardMember();
		record.setGmtCreate(new Date());
		record.setGmtModified(new Date());
		record.setMemberId(Long.parseLong(memberId));
		record.setOilcardType(oilcardType);
		record.setOilcardNumber(oilcardNumber);
		record.setOilcardPhone(oilcardPhone);
		record.setOilcardName(oilcardOwen);
		record.setIsDefault(isDefault==1?Boolean.TRUE:Boolean.FALSE);
        result = ysOilcardMemberMapper.insert(record);

		return result;
	}

	//增加油卡
	public Response deleteOilCard(Long memberId,Long oilcardId,String groupCode) throws Exception{
		Response request = new Response();
		
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupCode);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		YsOilcardMember ysOilcardMember= ysOilcardMemberMapper.selectByPrimaryKey(oilcardId);
	    if (ysOilcardMember==null||businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}
	    if(!ysOilcardMember.getMemberId().equals(memberId)){
	    	return request.format(false, 0, "非法操作", null);
	    }
		int result = ysOilcardMemberMapper.deleteByPrimaryKey(ysOilcardMember.getId());
		
		if(result>=0){
			return  request.format(true, 1, "操作成功", null);
		}
		return  request.format(false, 0, "删除失败", null);
	}

	//更新油卡
	public Response updateOilCard(Long memberId,Long oilcardId,String oilcardNumber,String oilcardOwen,String oilcardPhone,String oilcardType,Integer isDefault,String groupCode) throws Exception{
		Response request = new Response();
		Group businessBase = this.groupMapper.selectGroupByPayCode(groupCode);
		Member member = this.memberMapper.selectByPrimaryKey(memberId);
		YsOilcardMember ysOilcardMember= ysOilcardMemberMapper.selectByPrimaryKey(oilcardId);
	    if (ysOilcardMember==null||businessBase == null || member == null || member.getGroupId().longValue() != businessBase.getId().longValue()) {
			/**
			 * 会员不是当前商户的
			 */
			return request.format(false, 0, "非法操作", null);
		}
	    if(!ysOilcardMember.getMemberId().equals(memberId)){
	    	return request.format(false, 0, "非法操作", null);
	    }

		int count = 0;
		if(!Tools.isEmpty(oilcardNumber)) {
			count = ysOilcardMemberMapper.selectCardNumberCount(memberId, oilcardNumber,oilcardId);
			if (count > 0)
				throw new ApplicationException(Rescode.FAIL, "油卡号重复！");
		}
		if((isDefault!=null&&isDefault==1)) {
			//更新其它金额
			count = ysOilcardMemberMapper.updateRecordToUnDefault(memberId);

		}
		
		YsOilcardMember recordUpdate = new YsOilcardMember();
		recordUpdate.setGmtModified(new Date());
		recordUpdate.setId(oilcardId);
		recordUpdate.setOilcardNumber(oilcardNumber);
		recordUpdate.setOilcardName(oilcardOwen);
		recordUpdate.setOilcardPhone(oilcardPhone);
		recordUpdate.setOilcardType(oilcardType);
		recordUpdate.setIsDefault((isDefault!=null&&isDefault==1)?Boolean.TRUE:Boolean.FALSE);
		int result = ysOilcardMemberMapper.updateByPrimaryKeySelective(recordUpdate);

		if(result>=0){
			return  request.format(true, 1, "操作成功", null);
		}
		return  request.format(false, 0, "删除失败", null);

	}

	public Map<String, Object> getOilCardPackageList(String memberId,Integer isStartuse) throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL,"memberId 不能为空！");
		}
		if(isStartuse != null && isStartuse != 0 && isStartuse != 1) {
			throw new ApplicationException(Rescode.FAIL, "isStartuse 值不对！");
		}

		//取得交易优惠限额
		int maxAmount = ysOilcardMemberMapper.selectYsDiscountLimitAmount(Long.parseLong(memberId));
		if(maxAmount==0)
			maxAmount = 999999999;
		else{
			String startDate=SysUtils.formatDate(new Date(), "yyyy-MM");
			maxAmount = maxAmount - ysOilcardOrderMapper.findRechargeAmount(memberId,startDate);
		}
		map.put("maxAmount", maxAmount);
		//

		List<YsOilcard> ysOilcardList = ysOilcardMapper.selectOilcardList(isStartuse);
		List<Map<String,Object>> oilCardList = new ArrayList<Map<String, Object>>();
		for(YsOilcard ysOilcard:ysOilcardList){
			Map<String, Object> detail = new HashMap<String, Object>();
			detail.put("id",ysOilcard.getId());
			detail.put("gmtCreate", DateUtil.fomatDate(ysOilcard.getGmtCreate(),DateUtil.sdfTime));
			detail.put("gmtModified", DateUtil.fomatDate(ysOilcard.getGmtModified(),DateUtil.sdfTime));
			detail.put("sort", ysOilcard.getSort());
			detail.put("discount",ysOilcard.getDiscount());
			detail.put("oilcardType", ysOilcard.getOilcardType());
			detail.put("isDefault", ysOilcard.getIsDefault()?1:0);
			detail.put("count", ysOilcard.getCountNum());
			detail.put("limitamount", ysOilcard.getLimitAmount());
			detail.put("type", ysOilcard.getType());
			detail.put("isstartuse", ysOilcard.getIsStartuse());
			oilCardList.add(detail);
		}
		if(oilCardList.size()>0) {
			map.put("oilCardList", oilCardList);
		}
		return map;
	}

  
	
	@Override
	public List<OilCardDenominationBean> listOilcardDenomination(String oilcardType) {
		
		List<OilCardDenominationBean> list=new ArrayList<OilCardDenominationBean>();
		OilCardDenominationBean data1=new OilCardDenominationBean(10000);
		
		list.add(data1);
		OilCardDenominationBean data2=new OilCardDenominationBean(20000);
		
		list.add(data2);
		OilCardDenominationBean data3=new OilCardDenominationBean(50000);
		
		list.add(data3);
		OilCardDenominationBean data4=new OilCardDenominationBean(100000);
		
		list.add(data4);
		
		return list;
	}

	@Override
	public YsOilcard finishOidCardById(Long oilcardPackageId) {
		return  ysOilcardMapper.selectByPrimaryKey(oilcardPackageId);
	}


	@Override
	public List<YsOilcard> listOilcard(String oilcardType, String businessCode) {
		Group group=groupMapper.selectGroupByPayCode(businessCode);
		return ysOilcardMapper.findOilCardListByType(oilcardType,group.getId());
	}


	@Override
	public int updateToDefault(String businessCode, Long memberId, Long id, Integer isdefault) throws Exception {
		
		
		if(isdefault.intValue()==1){
			//把默认的改为0
			int num = ysOilcardMemberMapper.updateRecordToUnDefault(memberId);
		}
		//改为默认
		YsOilcardMember  ysOilcardMember = ysOilcardMemberMapper.selectByPrimaryKey(id);
		if(ysOilcardMember!=null&&ysOilcardMember.getMemberId().longValue()==memberId){
			ysOilcardMember.setIsDefault(isdefault.intValue()==1?true:false);
		}else{
			return -1;
		}
		int num=ysOilcardMemberMapper.updateByPrimaryKeySelective(ysOilcardMember);
		if(num < 1){
			logger.error(id+"set default faild");
			throw new Exception("设置默认失败！");
		}
		return num;		
		
	}








	


	
}

